package com.yangle.shell.controller;

import com.yangle.shell.bean.ProductCategory;
import com.yangle.shell.bean.ProductInfo;
import com.yangle.shell.service.CategoryService;
import com.yangle.shell.service.ProductInfoService;
import com.yangle.shell.util.ProductRequestVoUtil;
import com.yangle.shell.vo.ProductCategoryVo;
import com.yangle.shell.vo.ProductInfoVo;
import com.yangle.shell.vo.ProductRequestVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Author: yangle
 * Create Data: 2020/12/4
 */
@RestController
@RequestMapping("/buyer/product")
public class ProductController {

    @Autowired
    private ProductInfoService productInfoService;

    @Autowired
    private CategoryService categoryService;

    @RequestMapping("/list")
    public ProductRequestVo getProductList(){
        /**查询所有上架的商品及其所属类目返回到页面
         * 1.查询所有上架的商品
         * 2.查询所有商品类目
         * 3.将查询的所有数据进行格式封装返回给前端
         * */
        List<ProductInfo> productInfoList = productInfoService.getUpAll();
        List<Integer> list1 = new ArrayList<>();
        //这里传进来的类目categoryType的list集合，需要从查出来的商品里去取
        //这样才能拿到每个商品对应的商品类目
        List<Integer> list =productInfoList.stream()
                .map(e->e.getCategoryType())
                .collect(Collectors.toList());
        System.out.println("stream:"+list);
        for(ProductInfo productInfo:productInfoList){
            list1.add(productInfo.getCategoryType());
        }
        System.out.println("for:"+list1);
        List<ProductCategory> productCategoryList = categoryService.findByCategoryTypeIn(list);
        List<ProductCategoryVo> productCategoryVos = new ArrayList<>();
        for(ProductCategory productCategory:productCategoryList){
            ProductCategoryVo productCategoryVo = new ProductCategoryVo();
            productCategoryVo.setCategoryName(productCategory.getCategoryName());
            productCategoryVo.setCategoryType(productCategory.getCategoryType());
            List<ProductInfoVo> productInfoVos = new ArrayList<>();
            for(ProductInfo productInfo:productInfoList){
                //必须是商品的类目和当前类目相同，才将商品放入该类目下
                if(productInfo.getCategoryType().equals(productCategory.getCategoryType())){
                    ProductInfoVo productInfoVo = new ProductInfoVo();
                    BeanUtils.copyProperties(productInfo,productInfoVo);
                    productInfoVos.add(productInfoVo);
                }
            }
            productCategoryVo.setProductInfoVoList(productInfoVos);
            productCategoryVos.add(productCategoryVo);
        }

        return ProductRequestVoUtil.success(productCategoryVos);
    }
}
